package com.yj.springbootmybatis.rest.center;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yj.springbootmybatis.pojo.User;
import com.yj.springbootmybatis.pojo.center.UserInfoBo;
import com.yj.springbootmybatis.resource.UploadResource;
import com.yj.springbootmybatis.service.center.CenterService;
import com.yj.springbootmybatis.util.CookieUtils;
import com.yj.springbootmybatis.util.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Api(value = "用户中心模块",tags = "用户中心模块接口")
@RequestMapping("center")
@RestController
public class CenterController {

    @Autowired
    CenterService centerService;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    UploadResource uploadResource;


    @ApiOperation(value = "根据用户id查询用户信息")
    @GetMapping("userInfo")
    public ResponseUtil userInfo(@RequestParam @ApiParam(value = "用户id") String userId){
        if (StringUtils.isBlank(userId)){
            return ResponseUtil.error().message("用户id不能为空!");
        }

        User user = centerService.queryUserInfo(userId);
        return ResponseUtil.success().data(user);

    }

    @ApiOperation(value = "根据用户id更新用户头像")
    @PostMapping("updatePhoto")
    public ResponseUtil updatePhoto(@RequestParam @ApiParam(value = "用户id")String userId, @RequestParam MultipartFile file,HttpServletRequest req,HttpServletResponse resp) throws Exception {

        if (StringUtils.isBlank(userId)){
            return ResponseUtil.error().message("用户id不能为空！");
        }
        if (null != file){
            String realFileName = file.getOriginalFilename();
//            String path = "D:"+File.separator+"images";
            String path = uploadResource.getUploadFilePath();

            if (!StringUtils.isBlank(realFileName)){
                String[] split = realFileName.split("\\.");
                String suffix = split[split.length-1]; //获取文件的后缀
                System.out.println(suffix);
                if (!StringUtils.equalsIgnoreCase(suffix,"png") && !StringUtils.equalsIgnoreCase(suffix,"jpg")){
                    return ResponseUtil.error().message("图片文件格式不正确！");
                }

                String imagesPath = "faceImages-" + userId + "." +suffix;
                String finalPath = path + File.separator + userId + File.separator+ imagesPath;

                File file1 = new File(finalPath);

                if (file1.getParentFile()!=null){
                    file1.getParentFile().mkdirs();
                }

                String faceUrl = uploadResource.getFaceUrl() + userId +"/"+imagesPath;
                User user = centerService.updateUserPhoneById(userId, faceUrl);
                user.setFace(user.getFace() + "?t=" +  RandomUtil.randomNumbers(9));
                user = setNullProperty(user);

                String valueAsString = objectMapper.writeValueAsString(user);

                CookieUtils.addCookieInfo(userId,valueAsString,req,resp);

                //文件保存到指定目录
                OutputStream os = new FileOutputStream(file1);
                InputStream is = file.getInputStream();
                IoUtil.copy(is,os);
            }
        }
        return ResponseUtil.success();

    }


    @ApiOperation(value = "根据用户id更新用户信息")
    @PostMapping("update")
    public ResponseUtil update(@RequestParam @ApiParam(value = "用户id") String userId, @RequestBody @Valid UserInfoBo userInfoBo, BindingResult result, HttpServletRequest req, HttpServletResponse resp) throws JsonProcessingException {
        if (StringUtils.isBlank(userId)){
            return ResponseUtil.error().message("用户id不能为空!");
        }

        if (result.hasErrors()){
            Map<String, String> errorMap = errorMap(result);
            return ResponseUtil.error().data(errorMap);
        }

        User user = centerService.updateUserInfoById(userId,userInfoBo);

        user = setNullProperty(user);

        String valueAsString = objectMapper.writeValueAsString(user);

        CookieUtils.addCookieInfo(userId,valueAsString,req,resp);
        //todo:后续要改，增加令牌token，整合redis，分布式会话
        return ResponseUtil.success();

    }

    public Map<String,String> errorMap(BindingResult result){
        List<FieldError> fieldErrors = result.getFieldErrors();
        Map<String,String> map = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            map.put(field,defaultMessage);
        }
        return map;
    }

    public User setNullProperty(User user){
        user.setPassword(null);
        user.setMobile(null);
        user.setEmail(null);
        user.setCreateTime(null);
        return user;
    }

}
